package com.xiaotu.spider.iqy.pageprocessor;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.TVProcessDataModel;
import com.xiaotu.common.util.*;
import com.xiaotu.spider.APageProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;

import java.util.*;

/**
 * 爱奇艺热度 电视剧，网剧，网大 (数据来源于骨朵)
 *
 * @author zhangxiao
 * @create 2021-01-21 17:09
 */
@Component("IQYHeatPageProcessor")
public class IQYHeatPageProcessor extends APageProcessor {
    private Map<String, String> headers = null;

    {
        headers = new HashMap<String, String>();
        headers.put("Accept", PropertiesUtil.getProperty("GuDuo.site.Accept"));
        headers.put("Accept-Encoding", PropertiesUtil.getProperty("GuDuo.site.Accept-Encoding"));
        headers.put("Accept-Language", PropertiesUtil.getProperty("GuDuo.site.Accept-Language"));
        headers.put("Cache-Control", PropertiesUtil.getProperty("GuDuo.site.Cache-Control"));
        headers.put("Connection", PropertiesUtil.getProperty("GuDuo.site.Connection"));
        headers.put("Cookie", PropertiesUtil.getProperty("GuDuo.site.Cookie"));
        headers.put("Host", PropertiesUtil.getProperty("GuDuo.site.Host"));
        headers.put("User-Agent", PropertiesUtil.getProperty("GuDuo.site.User-Agent"));
    }

    //搜索列表
    public static final String SIMPLE_DETAIL =
            "http://ev.guduodata.com/show/simpleDetail/%s";

    //爱奇艺热度
    public static final String IQY_HEAT =
            "http://ev.guduodata.com/show/hotCount/%s";

    @Override
    protected Request getStartRequest(JSONObject target) {
        return new Request("http://ev.guduodata.com/show/like?name="
                + KeywordEncode.encode(target.getString("tvName")));
    }

    @Override
    public String getPageDataType(Page page) {
        String url = page.getUrl().toString();
        if (url.contains("/show/like?name="))
            return Constants.PageDataType.SEARCH_LIST;
        else if (url.contains("/show/hotCount"))
            return Constants.PageDataType.TV_RECORD;
        else
            return null;
    }

    @Override
    public void process(Page page) {
        Map<String, Object> tvMap = page.getRequest().getExtras();
        switch (this.getPageDataType(page)) {
            case Constants.PageDataType.SEARCH_LIST:
                this.searchListProcess(page, tvMap);
                break;
            case Constants.PageDataType.TV_RECORD:
                this.tvRecordProcess(page, tvMap);
                break;
            default:
                break;
        }
    }

    private void searchListProcess(Page page, Map<String, Object> tvMap) {
        String rawText = page.getRawText();
        if (org.apache.commons.lang.StringUtils.isEmpty(rawText))
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);
        JSONObject jsonObject = JSONObject.fromObject(rawText);
        JSONArray list = jsonObject.getJSONObject("data").getJSONArray("list");
        list.stream().forEach(j -> {
            String jsonp = HttpUtils.httpGetJSONP(String.format(SIMPLE_DETAIL, ((JSONObject) j).getString("id")), headers);
            if (org.apache.commons.lang.StringUtils.isEmpty(jsonp))
                throw new SpiderException(
                        SpiderExceptionCode.DataInvalideException);
            JSONObject detailObject = JSONObject.fromObject(jsonp);
            String pageTvType = TVProcessUtils.getTVType(detailObject.getString("category"));
            JSONArray actor_info_list = detailObject.getJSONArray("actor_info");
            List<String> pageActors = new ArrayList<String>();
            actor_info_list.stream().limit(10).forEach(actor -> {
                JSONObject actorInfo = (JSONObject) actor;
                pageActors.add(actorInfo.getString("actorName"));
            });
            String pageTvName = detailObject.getString("show_name");
            List<String> pageDirectors = Arrays.asList(detailObject.getString("director").split("[/,，]"));
            if (TVProcessUtils.tvMatched(tvMap, pageTvName, pageTvType, pageActors, pageDirectors)) {
                PageUtils.addTargetRequest(page, String.format(IQY_HEAT, ((JSONObject) j).getString("id")), tvMap);
            }
        });

    }


    private void tvRecordProcess(Page page, Map<String, Object> tvMap) {
        String res = page.getRawText();
        if (StringUtils.isEmpty(res))
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);
        JSONObject jsonObject = JSONObject.fromObject(res);
        String todayIQYHeat = jsonObject.getJSONObject("data").getString("today_hot_count");
        if (StringUtils.isEmpty(todayIQYHeat))
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);
        page.putField(TVProcessDataModel.class.getName(), new TVProcessDataModel(tvMap.get("tvid").toString(),
                tvMap.get("tvName").toString(),
                Constants.SiteName.IQIYI, null, todayIQYHeat, null));
    }

    @Override
    protected String getSpiderType() {
        return Constants.SpiderTaskType.TV_GUDUO;
    }
}
